package com.bocloud.controller;

import com.bocloud.model.Login;
import com.bocloud.model.Result;
import com.bocloud.mq.SendMessage;
import com.bocloud.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    SendMessage sendMessage;

    /**
     * 用途：用户登录，根据用户名和密码查询,有数据则登录成功，反之，登录失败
     *
     * @param login
     * @return ：Result 查询到数据返回true，反之，返回flase
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Result login(@RequestBody Login login, HttpServletRequest request, HttpSession session) {
        if (loginService.select(login) == null) {
            return new Result(false, "用户不存在");
        } else {
            if (loginService.getLogin(login) != null) {
                request.getSession().setAttribute(session.getId(), login);
                //System.out.println(session.getAttribute("login"));
                return new Result(true, "登录成功");
            } else {
                return new Result(false, "密码错误");
            }
        }

    }

    /**
     * 用途：用户注册，先查询用户是否存在，存在则返回flase，反之，新增一条数据
     *
     * @param login
     * @return ：Result
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public Result register(@RequestBody Login login) {
        if (loginService.select(login) != null) {
            return new Result(false, "用户名已存在");
        } else {
            if (loginService.addLogin(login)) {
                sendMessage.send(login);
                //sendMessage.send1(login);
                //sendMessage.send2(login);
                //sendMessage.send3(login);
                return new Result(true, "注册成功");
            } else {
                return new Result(false, "注册失败");
            }
        }
    }


}

